package f_socketChat;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
/**
 * 发送数据线程
 * @author Y
 *
 */
public class Send implements Runnable{
	
	//控制台的输入流
	private BufferedReader console;
	//管道的输出流
	private DataOutputStream dos;
	//控制线程
	private boolean isRunning = true;
	//名称
	private String name;
	
	/**
	 * 提供无参构造
	 */
	public Send() {
		console= new BufferedReader(new InputStreamReader(System.in));
	}
	
	/**
	 * 提供有参构造方法
	 * @param client
	 * @param name
	 */
	public Send(Socket client, String name) {
		//初始化无参
		this();
		try {
			dos= new DataOutputStream(client.getOutputStream());
			this.name=name;
			send(this.name);
			
		} catch (IOException e) {
			isRunning = false;
			CloseUtil.closeAll(dos,console);
		}
		
	}
	
	/**
	 * 从控制台接受数据
	 * @return
	 */
	private String getMsgFromConsole(){
		try {
			return console.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 从控制台接受数据
	 * 发送数据
	 * @param msg
	 */
	private void send(String msg) {
		if (msg != null && !msg.equals("")) {
			try {
				//向管道写入数据
				dos.writeUTF(msg);
				//强制刷新
				dos.flush();
			} catch (IOException e) {
				System.err.println("用户写入数据异常:"+e.getMessage());
				isRunning = false;
				CloseUtil.closeAll(dos,console);
			}
			
		}
	}

	@Override
	public void run() {
		//线程体
		while (isRunning) {
			//
			send(getMsgFromConsole());
		}
	}

	
}
